<template>
  <Drawer
    v-model="show"
    :title="title"
    :size="500"
    @close="show = false"
  >
    <template #content>
      <el-form
        label-width="150px"
        :model="form"
        :rules="rules"
        ref="formRef"
        v-loading="formLoading"
      >
        <el-form-item label="所属企业" prop="enterId">
          <el-select
            filterable
            v-model="form.enterId"
            placeholder="请选择所属企业"
            :disabled="title === '编辑'"
            @change="outTenantChange"
            class="!w-250px"
          >
            <el-option
              v-for="item in tenantList"
              :key="item.id"
              :label="item.enterName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户企业" prop="cusId">
          <el-select
            filterable
            v-model="form.cusId"
            placeholder="请选择客户企业"
            :disabled="title === '编辑'"
            class="!w-250px"
          >
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址名称" prop="cusAddress">
          <el-input
            :maxlength="50"
            v-model="form.cusAddress"
            placeholder="请输入地址名称"
            class="!w-250px"
          />
        </el-form-item>
        <el-form-item label="销售方向" prop="cusSales">
          <el-select
            filterable
            v-model="form.cusSales"
            placeholder="请选择销售方向"
            class="!w-250px"
          >
            <el-option
              v-for="item in getIntJLDictOptions(
                DICT_TYPE.CUS_SALES
              )"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="cusProvince">
          <el-select
            filterable
            v-model="form.cusProvince"
            placeholder="请选择省"
            @change="provinceChange"
            class="!w-250px"
          >
            <el-option
              v-for="item in regionObj.province"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="cusCity">
          <el-select
            filterable
            v-model="form.cusCity"
            placeholder="请选择市"
            @change="cityChange"
            class="!w-250px"
          >
            <el-option
              v-for="item in regionObj.city"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="cusCounty">
          <el-select
            filterable
            v-model="form.cusCounty"
            placeholder="请选择区县"
            @change="countyChange"
            class="!w-250px"
          >
            <el-option
              v-for="item in regionObj.county"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乡镇街道" prop="cusTown">
          <el-select
            filterable
            v-model="form.cusTown"
            placeholder="请选择乡镇街道"
            class="!w-250px"
          >
            <el-option
              v-for="item in regionObj.town"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="common" @click="closeDrawer">
        取消
      </el-button>
      <el-button
        type="primary"
        :disabled="formLoading"
        @click="submitForm"
      >
        确认
      </el-button>
    </template>
  </Drawer>
</template>
<script lang="ts" setup>
import {
  DICT_TYPE,
  getIntJLDictOptions
} from '@/utils/dict'
import * as unloadingAddressApi from '@/api/unloadingAddress'
import * as authorizationManageApi from '@/api/authorizationManage'
import * as salesPlanApi from "@/api/salesPlan";

const formRef = ref()
const show = ref(false)
const formLoading = ref(false)
const title = ref('新增')
const emit = defineEmits(['success'])
const message = useMessage()
const form = ref({
  id: undefined,
  enterId: undefined,
  cusId: undefined,
  cusAddress: undefined,
  cusSales: undefined,
  cusProvince: undefined,
  cusCity: undefined,
  cusCounty: undefined,
  cusTown: undefined
})
const tenantList: Record<string, any> = ref([])
const customerList: Record<string, any> = ref([])
const regionObj: Record<string, any> = ref({
  province: [],
  city: [],
  county: [],
  town: []
})

const rules = reactive({
  enterId: [
    {
      required: true,
      message: '请选择所属企业',
      trigger: 'change'
    }
  ],
  cusId: [
    {
      required: true,
      message: '请选择客户企业',
      trigger: 'change'
    }
  ],
  cusAddress: [
    {
      required: true,
      message: '请输入地址名称',
      trigger: 'blur'
    }
  ],
  cusSales: [
    {
      required: true,
      message: '请选择销售方向',
      trigger: 'change'
    }
  ],
  cusProvince: [
    {
      required: true,
      message: '请选择省',
      trigger: 'change'
    }
  ],
  cusCity: [
    {
      required: true,
      message: '请选择市',
      trigger: 'change'
    }
  ],
  cusCounty: [
    {
      required: true,
      message: '请选择区县',
      trigger: 'change'
    }
  ],
  cusTown: [
    {
      required: true,
      message: '请选择乡镇街道',
      trigger: 'change'
    }
  ]
})

const open = async (id) => {
  title.value = id ? '编辑' : '新增'
  resetForm()
  initDetail(id)
  show.value = true
}

const initDetail = async (id) => {
  try {
    formLoading.value = true
    await getOutTenantList()
    await getRegionCnById('0', 'province')
    if (id) {
      getSaleCustomerAddressById(id)
    }
  } finally {
    formLoading.value = false
  }
}

const getSaleCustomerAddressById = async (id) => {
  const res =
    await unloadingAddressApi.getSaleCustomerAddressById(id)
  if (res.enterId) {
    await getCustomerList(res.enterId)
  }
  if (res.cusProvince) {
    await getRegionCnById(res.cusProvince, 'city')
  }
  if (res.cusCity) {
    await getRegionCnById(res.cusCity, 'county')
  }
  if (res.cusCounty) {
    await getRegionCnById(res.cusCounty, 'town')
  }
  Object.keys(form.value).forEach((key) => {
    if (
      [
        'cusProvince',
        'cusCity',
        'cusCounty',
        'cusTown'
      ].includes(key)
    ) {
      form.value[key] = [null, undefined].includes(res[key])
        ? ''
        : Number(res[key])
    } else {
      form.value[key] = res[key]
    }
  })
}

const getOutTenantList = async () => {
  const res =
    await authorizationManageApi.getOutTenantList()
  tenantList.value = res || []
}

const outTenantChange = () => {
  customerList.value = []
  form.value.cusId = undefined
  if (form.value.enterId) {
    getCustomerList(form.value.enterId)
  }
}

const getCustomerList = async (outTenantId) => {
  const res =
    await unloadingAddressApi.getCustomerListByIdentity({
      outTenantId,
      identity: 1
    })
  customerList.value = res || []
}

const provinceChange = () => {
  form.value.cusCity = undefined
  form.value.cusCounty = undefined
  form.value.cusTown = undefined
  regionObj.value.city = []
  regionObj.value.county = []
  regionObj.value.town = []
  getRegionCnById(form.value.cusProvince, 'city')
}

const cityChange = () => {
  form.value.cusCounty = undefined
  form.value.cusTown = undefined
  regionObj.value.county = []
  regionObj.value.town = []
  getRegionCnById(form.value.cusCity, 'county')
}

const countyChange = () => {
  form.value.cusTown = undefined
  regionObj.value.town = []
  getRegionCnById(form.value.cusCounty, 'town')
}

const getRegionCnById = async (id, type) => {
  const res = await unloadingAddressApi.getRegionCnById(id)
  regionObj.value[type] = res || []
}

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    if (form.value.id) {
      await updateSaleCustomerAddress()
    } else {
      await addSaleCustomerAddress()
    }
  } finally {
    formLoading.value = false
  }
}
const router = useRouter()
const updateSaleCustomerAddress = async () => {
  const res = await unloadingAddressApi.updateSaleCustomerAddress(
    form.value
  )
  if (res.code === 0) {
    message.success('修改成功')
    emit('success')
    show.value = false
  } else if (res.code === 100910003) {
    await message.confirm(res.msg)
    refreshAuthorize()
  } else if (res.code === 100910004) {
    await message.confirm(res.msg)
    router.push({path: '/authManageCatalog/authorizationManage'})
  } else {
    message.error(res.msg)
  }
}

const refreshAuthorize = async () => {
  await salesPlanApi.refreshAuthorize()
}

const addSaleCustomerAddress = async () => {
  const res = await unloadingAddressApi.addSaleCustomerAddress(
    form.value
  )
  if (res.code === 0) {
    message.success('新增成功')
    emit('success')
    show.value = false
  } else if (res.code === 100910003) {
    await message.confirm(res.msg)
    refreshAuthorize()
  } else if (res.code === 100910004) {
    await message.confirm(res.msg)
    router.push({path: '/authManageCatalog/authorizationManage'})
  } else {
    message.error(res.msg)
  }
}

const closeDrawer = () => {
  show.value = false
}

const resetForm = () => {
  form.value = {
    id: undefined,
    enterId: undefined,
    cusId: undefined,
    cusAddress: undefined,
    cusSales: undefined,
    cusProvince: undefined,
    cusCity: undefined,
    cusCounty: undefined,
    cusTown: undefined
  }
  tenantList.value = []
  customerList.value = []
  regionObj.value = {
    province: [],
    city: [],
    county: [],
    town: []
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
<style lang="scss" scoped></style>
